<template>
  <el-form
    :model="ruleForm"
    status-icon
    :rules="rules"
    ref="ruleForm"
    label-width="150px"
    class="demo-ruleForm"
  >
    <el-form-item label="添加商品名称" prop="name">
      <el-input
        clearable
        type="text"
        v-model="ruleForm.name"
        placeholder="不超过20个字"
        autocomplete="off"
      ></el-input>
    </el-form-item>

    <el-form-item label="商品简称">
      <el-input v-model="ruleForm.shortName"></el-input>
    </el-form-item>

    <el-form-item label="商品所属分类" prop="categoryId">
      <el-select
        v-model="ruleForm.categoryName"
        placeholder="所属分类"
        class="handle-select mr10"
        @change="handleSelect"
        clearable
      >
        <el-option
          v-for="(item, index) in cateList"
          :key="index"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="供应商" prop="companyId">
      <el-select
        v-model="ruleForm.companyId"
        placeholder="选择供应商"
        class="handle-select mr10"
        @change="handleSelectCompany"
        clearable
      >
        <el-option
          v-for="(item, index) in supplierList"
          :key="index"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="备注">
      <el-input v-model="ruleForm.memo"></el-input>
    </el-form-item>
    <el-form-item label="是否上架" prop="enableStatus">
      <el-select
        v-model="ruleForm.enableStatus"
        placeholder="是否上架"
        class="handle-select mr10"
        clearable
      >
        <el-option key="0" label="上架" value="0"></el-option>
        <el-option key="1" label="下架" value="1"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="添加简介" prop="brief">
      <el-input
        clearable
        type="textarea"
        maxlength="200"
        placeholder="请输入商品介绍,不超过200个字"
        v-model.number="ruleForm.brief"
      ></el-input>
    </el-form-item>
    <el-form-item label="商品兑换所需积分" prop="integral">
      <el-input
        clearable
        type="text"
        placeholder="商品积分"
        v-model="ruleForm.integral"
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item label="商品价格" prop="price">
      <el-input
        clearable
        type="text"
        placeholder="商品价格"
        v-model="ruleForm.price"
        autocomplete="off"
      ></el-input>
    </el-form-item>

    <el-form-item label="添加商品详情图" prop="image">
      <el-upload
        accept=".jpg,.jpeg,.png"
        list-type="picture-card"
        :auto-upload="true"
        :http-request="uploadFile"
        action="customize"
        :file-list="fileList"
        :limit="8"
        :on-remove="handleRemove"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </el-form-item>

    <el-form-item>
      <el-button @click="cancelForm('ruleForm')">取消</el-button>
      <el-button type="primary" @click="submitForm()">提交</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import util from "utils/util";
export default {
  data() {
    var validatePrice = function(rule, value, callback) {
      if (value && parseInt(value) < 0) {
        return callback(new Error("价格不能为负值"));
      } else if (value.trim() == "") {
        return callback(new Error("必填不能为空"));
      }
      callback();
    };
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      // radio: "",
      fileList: [],
      ruleForm: {
        name: "",
        categoryId: "",
        brief: "",
        integral: "",
        price: "",
        shortName: "",
        companyId: "",
        memo: "",
        enableStatus: "",
        imageUrlList: [],
        // radio: ""
        // commodityImageDTO: [] // 新增图片时缺失
      },
      // commodityImageDTO: [],
      rules: {
        name: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        categoryId: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        brief: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        integral: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        price: [{ required: true, validator: validatePrice, trigger: "blur" }],
        image: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        // shortName: [
        //   { required: true, message: "必填不能为空", trigger: "blur" }
        // ],
        companyId: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        // memo: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        enableStatus: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
      },
      sort: 0,
      cateList: [],
      supplierList: [],
    };
  },
  methods: {
    // 上传图片
    uploadFile(params) {
      const _file = params.file;
      const isLt2M = _file.size / 1024 / 1024 < 2;
      var formData = new FormData();
      formData.append("file", _file);
      if (!isLt2M) {
        this.$message.error("请上传2M以下的.图片文件");
        return false;
      }
      this.$axios
        .post("/sys/oss/uploadCommodityImage", formData)
        .then(({ data: res }) => {
          console.log("图片链接", res);
          if (res.code != 0) {
            return;
          }
          console.log(this.fileList);
          var imageUrlList = this.ruleForm.imageUrlList;
          var sort = this.sort;
          sort = imageUrlList.length;
          this.sort = sort;
          imageUrlList.push({
            imageUrl: res.data.src,
            enableStatus: 0,
            sort: sort,
          });
          sort++;
          console.log(this.ruleForm.imageUrlList);
          this.ruleForm.imageUrlList = imageUrlList;
          console.log(this.ruleForm);
        });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.ruleForm.imageUrlList = [];
      fileList.map((item, index) => {
        this.ruleForm.imageUrlList.push({
          imageUrl: item.url,
          enableStatus: 0,
          sort: index,
        });
      });

      // 编辑时删除
      // this.$axios
      //   .delete(`/product/commodityimage/imageUrl?imageUrl=${file.url}`, {})
      //   .then(({ data: res }) => {
      //     console.log(res);
      //     if (res.code != 0) {
      //       return;
      //     }
      //     this.$message.success("删除成功");
      //   })
      //   .catch(() => {});
    },
    // 所属分类
    handleSelect(categoryId) {
      console.log("所属分类id", categoryId);
      this.ruleForm.categoryId = categoryId;
    },
    // 供应商
    handleSelectCompany(companyId) {
      console.log("供应商", companyId);
      this.ruleForm.companyId = companyId;
    },
    // 是否热销
    // handleChange(value) {
    //   console.log(value);
    //   var commodityId = this.ruleForm.id;
    //   if (value == 0) {
    //     this.$axios
    //       .post("product/hotcakes", {
    //         commodityId
    //       })
    //       .then(({ data: res }) => {
    //         if (res.code != 0) {
    //           return this.$message.error(res.msg);
    //         }
    //         this.$message.success("添加热销成功");
    //         console.log(res);
    //       })
    //       .catch(() => {});
    //   } else {
    //     this.$axios
    //       .delete(`product/hotcakes/${commodityId}`)
    //       .then(({ data: res }) => {
    //         if (res.code != 0) {
    //           return this.$message.error(res.msg);
    //         }
    //         this.$message.success("取消热销");
    //         console.log(res);
    //       })
    //       .catch(() => {});
    //   }
    // },
    // 获取编辑数据
    getEdit(id) {
      this.$axios
        .get(`/product/commodity/${id}`)
        .then(({ data: res }) => {
          console.log("编辑数据", res);
          if (res.code !== 0) {
            return;
          }
          var {
            id,
            name,
            categoryId,
            categoryName,
            brief,
            integral,
            price,
            shortName,
            companyId,
            memo,
            enableStatus,
            // commodityImageDTO,
            imageUrlList,
            // radio
          } = res.data;
          imageUrlList = imageUrlList.map((item, index) => {
            this.fileList.push({ url: item });
            return { imageUrl: item, enableStatus: 0, sort: index };
          });
          // console.log(imageUrlList);
          this.ruleForm = {
            id,
            name,
            categoryId,
            categoryName,
            brief,
            integral,
            price,
            shortName,
            companyId,
            memo,
            enableStatus,
            imageUrlList,
            // radio
          };
          console.log(this.ruleForm);
          this.ruleForm.enableStatus = this.ruleForm.enableStatus.toString();
        })
        .catch(() => {});
    },
    // 保存编辑
    submitForm() {
      var ruleForm = this.ruleForm;

      // 筛选必填项
      var {
        brief,
        categoryId,
        categoryName,
        companyId,
        enableStatus,
        id,
        imageUrlList,
        integral,
        name,
        price,
        // radio
      } = ruleForm;
      var required = {
        brief,
        categoryId,
        categoryName,
        companyId,
        enableStatus,
        id,
        imageUrlList,
        integral,
        name,
        price,
        // radio
      };

      console.log(ruleForm);
      // 判空处理
      var bool = util.isEmpty(required);
      if (bool) {
        return this.$message.error("必填项不能为空");
      }
      this.$axios
        .put("/product/commodity", {
          id: this.ruleForm.id,
          name: this.ruleForm.name,
          categoryId: this.ruleForm.categoryId,
          brief: this.ruleForm.brief,
          integral: this.ruleForm.integral,
          price: this.ruleForm.price,
          shortName: this.ruleForm.shortName,
          companyId: this.ruleForm.companyId,
          memo: this.ruleForm.memo,
          enableStatus: this.ruleForm.enableStatus,
          commodityImageDTO: this.ruleForm.imageUrlList,
        })
        .then(({ data: res }) => {
          console.log(res);
          if (res.code !== 0) {
            return;
          }
          this.$message.success("操作成功");

          // 跳转到商品管理
          this.$router.replace({
            path: "/product-manage",
          });
        })
        .catch(() => {});
    },
    extend(o1, o2) {},
    cancelForm(formName) {
      // this.$refs[formName].resetFields();
      this.$router.go(-1);
    },
    // 获取所属分类
    getProductCateList() {
      this.$axios
        .get("/product/commoditycategory/page", {
          params: {
            page: 1,
            limit: 100,
            enableStatus: 0,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          console.log("所属分类", res);
          this.cateList = res.data.list;
        })
        .catch(() => {});
    },
    // 获取供应商
    getSupplierList() {
      this.$axios
        .get("/product/company/page", {
          params: {
            page: 1,
            limit: 100,
            enableStatus: 0,
          },
        })
        .then(({ data: res }) => {
          console.log("供应商", res);
          if (res.code !== 0) {
            return;
          }
          this.supplierList = res.data.list;
        });
    },
  },
  created() {
    var id = this.$route.query.id;
    this.getEdit(id);

    // 获取所属分类
    this.getProductCateList();
    // 获取供应商
    this.getSupplierList();
  },
};
</script>
<style lang="scss">
.el-input,
.el-textarea {
  width: 50%;
}
</style>
